package rbac.service;

import rabc.domain.dto.DeptDto;
import rabc.domain.entity.Dept;
import rabc.domain.vo.DeptVo;
import rabc.domain.vo.Result;

import java.util.Arrays;

/**
 * 业务层-部门
 *
 * @author 朱磊
 * @since 2025/4/20 21:41
 */
public class Deptservice {
    public static int DATA_SIZE = 100;
    public static Dept[] data = new Dept[DATA_SIZE+1];
    public static int idCounter = 1;

    public static <Dept> DeptVo convertToVo(Dept dept){
        return new DeptVo(dept.id,dept.name,dept.phone);
    }

    public static Dept createEntity(DeptDto dto, int id){
        Dept  dept = new Dept(dto.name,dto.phone);
        dept.id = id;
        return dept;
    }
    public static void updataEntity(DeptDto dto,Dept dept){
        dept.name = dto.name;
        dept.phone = dto.phone;
    }
    public static Result list(){
        DeptVo[] temp = new DeptVo[DATA_SIZE];
        int length=0;
        for (int i = 1; i < idCounter; i++) {

            if (data[i] != null) {
                temp[i] = convertToVo(data[i]);
            }
        }
        return Result.success("查询成功", Arrays.copyOf(temp,length));
    }
    public static Result create(DeptDto dto){
        if (idCounter > DATA_SIZE){
            return Result.failure("部门数据已满");
        }
        Dept dept = createEntity(dto,idCounter++);
        data[dept.id] = dept;
        return Result.success("创建成功",null);
    }
    public static boolean existsById(int id){
        return id>=1&&id<idCounter&&data[id]!=null;
    }
    public static Result update(DeptDto dto,int id){
        if (!existsById(id)){
            return Result.failure("部门不存在");
        }

        updataEntity(dto,data[id]);
        return Result.success("更新成功",null);
    }
    public static Result delete(int id){
        if (!existsById(id)){
            return Result.failure("部门不存在");
        }
        data[id]=null;
        return Result.success("删除成功",null);
    }
}
